package com.ten.mall.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.ten.mall.vo.MyMessage;
import com.ten.mall.vo.weixin.Button;
import com.ten.mall.vo.weixin.ClickButton;
import com.ten.mall.vo.weixin.Image;
import com.ten.mall.vo.weixin.ImageMessage;
import com.ten.mall.vo.weixin.Menu;
import com.ten.mall.vo.weixin.Music;
import com.ten.mall.vo.weixin.MusicMessage;
import com.ten.mall.vo.weixin.News;
import com.ten.mall.vo.weixin.NewsMessage;
import com.ten.mall.vo.weixin.Pay;
import com.ten.mall.vo.weixin.TextMessage;
import com.ten.mall.vo.weixin.ViewButton;
import com.thoughtworks.xstream.XStream;
/**
 * 消息封装类
 * @author liujun
 *
 */
public class MessageUtil {	
	
	public static final String MESSAGE_TEXT = "text";
	public static final String MESSAGE_NEWS = "news";
	public static final String MESSAGE_IMAGE = "image";
	public static final String MESSAGE_VOICE = "voice";
	public static final String MESSAGE_MUSIC = "music";
	public static final String MESSAGE_VIDEO = "video";
	public static final String MESSAGE_LINK = "link";
	public static final String MESSAGE_LOCATION = "location";
	public static final String MESSAGE_EVNET = "event";
	public static final String MESSAGE_SUBSCRIBE = "subscribe";
	public static final String MESSAGE_UNSUBSCRIBE = "unsubscribe";
	public static final String MESSAGE_CLICK = "CLICK";
	public static final String MESSAGE_VIEW = "VIEW";
	public static final String MESSAGE_SCANCODE= "scancode_push";
	//public static final String CREATE_MENU_URL="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN"
	/**
	 * xml转为map集合
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws DocumentException
	 */
	public static Map<String, String> xmlToMap(HttpServletRequest request) throws Exception{
		Map<String, String> map = new HashMap<String, String>();
		SAXReader reader = new SAXReader();
		
		InputStream ins = request.getInputStream();
		Document doc = reader.read(ins);
		
		Element root = doc.getRootElement();
		
		List<Element> list = root.elements();
		
		for(Element e : list){
			map.put(e.getName(), e.getText());
		}
		ins.close();
		return map;
	}
	
	/**
	 * 将文本消息对象转为xml
	 * @param textMessage
	 * @return
	 */
	public static String textMessageToXml(TextMessage textMessage){
		XStream xstream = new XStream();
		xstream.alias("xml", textMessage.getClass());
		return xstream.toXML(textMessage);
	}
	
	/**
	 * 组装文本消息
	 * @param toUserName
	 * @param fromUserName
	 * @param content
	 * @return
	 */
	public static String initText(String toUserName,String fromUserName,String content){
		TextMessage text = new TextMessage();
		text.setFromUserName(toUserName);
		text.setToUserName(fromUserName);
		text.setMsgType(MessageUtil.MESSAGE_TEXT);
		text.setCreateTime(new Date().getTime());
		text.setContent(content);
		return textMessageToXml(text);
	}
	
	/**
	 * 主菜单
	 * @return
	 */
	public static String menuText(){
		StringBuffer sb = new StringBuffer();
		sb.append("欢迎您的关注，请按照菜单提示进行操作：\n\n");
		sb.append("1、微信介绍\n");
		sb.append("2、公共服务\n");
		sb.append("3、词组翻译\n\n");
		sb.append("回复？调出此菜单。");
		return sb.toString();
	}
	
	public static String firstMenu(){
		StringBuffer sb = new StringBuffer();
		sb.append("第一个按钮");
		return sb.toString();
	}
	
	public static String secondMenu(){
		StringBuffer sb = new StringBuffer();
		sb.append("第二个按钮");
		return sb.toString();
	}
	
	public static String threeMenu(){
		StringBuffer sb = new StringBuffer();
		sb.append("词组翻译使用指南\n\n");
		sb.append("使用示例：\n");
		sb.append("翻译足球\n");
		sb.append("翻译中国足球\n");
		sb.append("翻译football\n\n");
		sb.append("回复？显示主菜单。");
		return sb.toString();
	}
	/**
	 * 图文消息转为xml
	 * @param newsMessage
	 * @return
	 */
	public static String newsMessageToXml(NewsMessage newsMessage){
		XStream xstream = new XStream();
		xstream.alias("xml", newsMessage.getClass());
		xstream.alias("item", new News().getClass());
		return xstream.toXML(newsMessage);
	}
	
	/**
	 * 图片消息转为xml
	 * @param imageMessage
	 * @return
	 */
	public static String imageMessageToXml(ImageMessage imageMessage){
		XStream xstream = new XStream();
		xstream.alias("xml", imageMessage.getClass());
		return xstream.toXML(imageMessage);
	}
	
	/**
	 * 音乐消息转为xml
	 * @param musicMessage
	 * @return
	 */
	public static String musicMessageToXml(MusicMessage musicMessage){
		XStream xstream = new XStream();
		xstream.alias("xml", musicMessage.getClass());
		return xstream.toXML(musicMessage);
	}
	/**
	 * 图文消息的组装
	 * @param toUserName
	 * @param fromUserName
	 * @return
	 */
	public static String initNewsMessage(String toUserName,String fromUserName,MyMessage msg){
		String message = null;
		List<News> newsList = new ArrayList<News>();
		NewsMessage newsMessage = new NewsMessage();
		
		News news = new News();
		news.setTitle(msg.getMessageTitle());
		news.setDescription(msg.getMessagDetail());
		news.setPicUrl(msg.getMessagePic());
		news.setUrl(msg.getMessageText());
		newsList.add(news);
		
		newsMessage.setToUserName(fromUserName);
		newsMessage.setFromUserName(toUserName);
		newsMessage.setCreateTime(new Date().getTime());
		newsMessage.setMsgType(MESSAGE_NEWS);
		newsMessage.setArticles(newsList);
		newsMessage.setArticleCount(newsList.size());
		
		message = newsMessageToXml(newsMessage);
		return message;
	}
	
	/**
	 * 组装图片消息
	 * @param toUserName
	 * @param fromUserName
	 * @return
	 */
	public static String initImageMessage(String toUserName,String fromUserName){
		String message = null;
		Image image = new Image();
		image.setMediaId("JTH8vBl0zDRlrrn2bBnMleySuHjVbMhyAo0U2x7kQyd1ciydhhsVPONbnRrKGp8m");
		ImageMessage imageMessage = new ImageMessage();
		imageMessage.setFromUserName(toUserName);
		imageMessage.setToUserName(fromUserName);
		imageMessage.setMsgType(MESSAGE_IMAGE);
		imageMessage.setCreateTime(new Date().getTime());
		imageMessage.setImage(image);
		message = imageMessageToXml(imageMessage);
		return message;
	}
	
	/**
	 * 组装音乐消息
	 * @param toUserName
	 * @param fromUserName
	 * @return
	 */
	public static String initMusicMessage(String toUserName,String fromUserName){
		String message = null;
		Music music = new Music();
		music.setThumbMediaId("WsHCQr1ftJQwmGUGhCP8gZ13a77XVg5Ah_uHPHVEAQuRE5FEjn-DsZJzFZqZFeFk");
		music.setTitle("see you again");
		music.setDescription("速7片尾曲");
		music.setMusicUrl("http://zapper.tunnel.mobi/Weixin/resource/See You Again.mp3");
		music.setHQMusicUrl("http://zapper.tunnel.mobi/Weixin/resource/See You Again.mp3");
		
		MusicMessage musicMessage = new MusicMessage();
		musicMessage.setFromUserName(toUserName);
		musicMessage.setToUserName(fromUserName);
		musicMessage.setMsgType(MESSAGE_MUSIC);
		musicMessage.setCreateTime(new Date().getTime());
		musicMessage.setMusic(music);
		message = musicMessageToXml(musicMessage);
		return message;
	}
	/**
	 * 组装菜单
	 * @return
	 */
	public static Menu initMenu(){
		Menu menu = new Menu();
		ClickButton button11 = new ClickButton();
		button11.setName("click菜单");
		button11.setType("click");
		button11.setKey("11");
		
		ViewButton button21 = new ViewButton();
		button21.setName("view菜单");
		button21.setType("view");
		button21.setUrl("http://www.imooc.com");
		
		ClickButton button31 = new ClickButton();
		button31.setName("扫码事件");
		button31.setType("scancode_push");
		button31.setKey("31");
		
		ClickButton button32 = new ClickButton();
		button32.setName("地理位置");
		button32.setType("location_select");
		button32.setKey("32");
		
		Button button = new Button();
		button.setName("菜单");
		button.setSub_button(new Button[]{button31,button32});
		menu.setButton(new Button[]{button11,button21,button});
		return menu;
	}
	
	public static String createMenu(String token,String menu) throws Exception{
		String url ="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token;
		
		String result =doPostStr(url,menu);
		return result;
	}
	
	/**
	 * POST请求
	 * @param url
	 * @param outStr
	 * @return
	 * @throws ParseException
	 * @throws IOException
	 */
	@SuppressWarnings("deprecation")
	public static String doPostStr(String url,String outStr) throws Exception{
		DefaultHttpClient client = new DefaultHttpClient();
		HttpPost httpost = new HttpPost(url);
		String result = null;
		httpost.setEntity(new StringEntity(outStr,"UTF-8"));
		HttpResponse response = client.execute(httpost);
		result = EntityUtils.toString(response.getEntity(),"UTF-8");
		return result;
	}
	/**
	 * 把 对象转换成xml
	 * @param <T>
	 * @param pay
	 * @return
	 */
	public static String objectToXml(Pay pay){
			XStream xstream = new XStream();
			xstream.alias("xml", pay.getClass());
			return xstream.toXML(pay);
		}
	
	/**  
     * xml 转 Map  
     * @param xml  
     * @return  
     */  
    public static Map<String,String> Dom2Map(String xml)  
    {  
        Map<String,String> map = new HashMap<String, String>();  
        Document doc = null;  
        try {  
            doc = DocumentHelper.parseText(xml);  
        } catch (DocumentException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }  
        if(doc ==null)  
            return map;  
        Element root = doc.getRootElement();  
      for (Iterator iterator = root.elementIterator(); iterator.hasNext();) {  
         Element e = (Element) iterator.next();  
         map.put(e.getName(), e.getText());  
      }  
      return map;  
    }  
    
    /*public static void main(String[] args) {
		String ss ="<xml>"+
	"<return_code><![CDATA[SUCCESS]]></return_code>"+
	"<return_msg><![CDATA[OK]]></return_msg>"+
	"<appid><![CDATA[wxd482ab4d4fbe5923]]></appid>"+
	"<mch_id><![CDATA[1418718602]]></mch_id>"+
	"<nonce_str><![CDATA[SCpxrZNgR1gBzPLX]]></nonce_str>"+
	"<sign><![CDATA[9059BE3919CC4A19CBDD75B5459F2910]]></sign>"+
	"<result_code><![CDATA[SUCCESS]]></result_code>"+
	"<transaction_id><![CDATA[4200000069201801250593081265]]></transaction_id>"+
	
	"<out_trade_no><![CDATA[SH201801251516448372]]></out_trade_no>"+
	
	"<out_refund_no><![CDATA[ST201801250133166624]]></out_refund_no>"+
	"<refund_id><![CDATA[50000105742018012503306229046]]></refund_id>"+
	"<refund_channel><![CDATA[]]>"+
	"</refund_channel>"+
	"<refund_fee>1</refund_fee>"+
	"<coupon_refund_fee>0</coupon_refund_fee>"+
	"<total_fee>1</total_fee>"+
	"<cash_fee>1</cash_fee>"+
	"<coupon_refund_count>0</coupon_refund_count>"+
	"<cash_refund_fee>1</cash_refund_fee>"+
	"</xml>";
		Map<String,String> map =Dom2Map(ss);
		System.out.println(map.get("coupon_refund_count"));
		System.out.println(map.get("result_code"));
		System.out.println(map.get("out_trade_no"));
		System.out.println(map.get("total_fee"));
	}*/
}
